package com.kedacom.ctsp.authority.service.simple;

import com.kedacom.ctsp.authority.dao.AreaDao;
import com.kedacom.ctsp.authority.entity.Area;
import com.kedacom.ctsp.authority.service.AreaService;
import com.kedacom.ctsp.lang.Validate;
import com.kedacom.ctsp.lang.validate.ValidationException;
import com.kedacom.ctsp.web.entity.param.QueryParamEntity;
import com.kedacom.ctsp.web.service.StatusEnum;
import com.kedacom.ctsp.web.service.simple.AbstractTreeSortService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;


@Service
@Slf4j
public class AreaServiceImpl extends AbstractTreeSortService<Area, String> implements AreaService{

    @Autowired
    private AreaDao areaDao;


    @Override
    public  String patch(String id, Area data) {
        return super.patch(id,data);
    }

    @Override
    public String insert(Area entity) {
        if (entity.getStatus() == null) {
            entity.setStatus(StatusEnum.ENABLE.ordinal());
        }
        // 检查区域编码重复
        if (!checkUnique(Area.CODE,entity.getCode()))
        {
            throw new ValidationException("auth.area.code.duplicated");
        }
        return super.insert(entity);
    }

    @Override
    public int submit(Area entity, String commandId, String comment) {

        int status;

        if(entity.getStatus() == StatusEnum.ENABLE.ordinal()){
            status = StatusEnum.DISABLE.ordinal();
        }else{
            status = StatusEnum.ENABLE.ordinal();
        }
       return areaDao.updateAreaStatusByPathLike(status,entity.getPath());
    }

    @Override
    public int submit(Collection<Area> datas, String commandId, String comment) {
        int status=0;
        Validate.notEmpty(datas,"auth.area.notexist");
        for (Area entity : datas) {
            if(entity.getStatus() == StatusEnum.ENABLE.ordinal()){
                status = StatusEnum.DISABLE.ordinal();
            }else{
                status = StatusEnum.ENABLE.ordinal();
            }
            areaDao.updateAreaStatusByPathLike(status,entity.getPath());
        }
        return status;
    }

    @Override
    public List<Area> selectAsTree(String id, QueryParamEntity param) {
        List<Area> nodes = this.selectAllChildNode(id, param);

        Area parentArea = this.get(id);
        if(null != parentArea) {
            parentArea.setParent(null);
            nodes.add(parentArea);
        }
        return this.convertToTree(nodes);
    }


}
